package JavaAboutInterview;


import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:周鹏
 * @date: 2020/12/11 11:21
 * @description:
 */
public class DeadLock {
     private  Object  A = new Object();
     private Object B = new Object();
//    public void run() {
//        System.out.println("开始执行线程");
//    }
//
//    public Object getA() {
//        return this.A;
//    }
//
//    public void setA(Object a) {
//        this.A = a;
//    }
//
//    public Object getB() {
//        return this.B;
//    }
//
//    public void setB(Object b) {
//        this.B = b;
//    }


        public static void main(String[] args) {
        DeadLock dl1 = new DeadLock();
        DeadLock dl2=new DeadLock();
        Runnable r1 = new Runnable() {
            public void run() {
                synchronized (dl1.A) {
                    while (true) {
                        String tName = Thread.currentThread().getName();
                        System.out.println("我是线程" + tName + ",我拿到了A对象的锁");

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("我需要拿B对象的锁啦");
                        synchronized (dl2.B) {
                            System.out.println("线程1开始跑了");
                        }
                    }
                }
            }
        };


        Runnable r2 = new Runnable() {
            public void run() {

                synchronized (dl1.B) {
                    while (true) {
                        String tName = Thread.currentThread().getName();
                        System.out.println("我是线程" + tName + ",我拿到了B对象的锁");

                        try {
                            Thread.sleep(3000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        System.out.println("我需要拿A对象的锁啦");
                        synchronized (dl2.A) {
                            System.out.println("线程2开始跑了");
                        }
                        ;
                    }
                }
            }
        };

        Thread t1 = new Thread(r1);
        t1.setName("t1");
        t1.start();


        Thread t2 = new Thread(r2);
        t2.setName("t2");
        t2.start();

    }
}